package com.mzy.linear_struct.subject;

/**
 * @Author: codermzy
 * @Date: 2024/04/25/下午5:53
 * @Description:
 */
public class 两个线程交替打印yield {

    public static final Object lock = new Object();
    public static boolean printNumber = false;

    public static void main(String[] args) {
        // Thread t1 = new Thread(() -> {
        //     for (char i = 'A'; i <= 'C'; i++) {
        //         while (printNumber) {
        //             Thread.currentThread().yield();
        //         }
        //         System.out.println(i);
        //         printNumber = true;
        //
        //     }
        // });
        //
        // Thread t2 = new Thread(() -> {
        //     for (int i = 1; i <= 3; i++) {
        //         while (!printNumber) {
        //             Thread.currentThread().yield();
        //         }
        //         System.out.println(i);
        //         printNumber = false;
        //
        //     }
        // });


        Thread t1 = new Thread(() -> {
            for (int i = 1; i <= 3; i++) {
                while (printNumber) {
                    Thread.yield();
                }
                System.out.println(i);
                printNumber = true;
            }
        });

        Thread t2 = new Thread(() -> {
            for (char c = 'A'; c <= 'C'; c++) {
                while (!printNumber) {
                    Thread.yield();
                }
                System.out.println(c);
                printNumber = false;
            }
        });


        t2.start();
        t1.start();
    }
}
